package logic

import (
	"context"
	"fmt"
	"product/model/cache"
	"product/model/mysql"
	"product/pkg"
	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 注册
func (l *RegisterLogic) Register(in *productrpc.RegisterRequest) (*productrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var finduser mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("请前去登陆")
	}

	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Account).Result()

	if result != in.SendCode {
		return nil, fmt.Errorf("验证码错误请重新输入")
	}

	user := mysql.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}
	mysql.DB.Debug().Create(&user)

	return &productrpc.RegisterResponse{
		Id: int64(finduser.ID),
	}, nil
}
